package com.lagou.coder;

import com.lagou.Serializer.Serializer;
import com.lagou.request.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author chenjr16@meicloud.com
 * @Description:
 * @ClassName: RpcDecoder
 * @date 2020-6-3 17:52
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        ByteBuf d = byteBuf.readBytes(byteBuf.readableBytes());
        byte[] x = new byte[d.readableBytes()];
        d.readBytes(x);

        byte[] bs = new byte[x.length - 4];
        System.arraycopy(x, 4, bs, 0, x.length - 4);
        RpcRequest deserialize = (RpcRequest) serializer.deserialize(clazz, bs);
        list.add(deserialize);
    }

}
